package cn.zzdt4j.config.springboot.starter.support;

import cn.zzdt4j.threadpool.dynamic.model.config.properties.AdapterExecutorProperties;
import cn.zzdt4j.threadpool.dynamic.model.config.properties.BootstrapConfigProperties;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.InitializingBean;

import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;

import static cn.zzdt4j.common.constant.Constants.IDENTIFY_SLICER_SYMBOL;

/**
 * Dynamic thread-pool adapter register
 *
 * @author by <a href="mailto:ligang941012@gmail.com">gang.Li</a>
 * @since 2024/5/15 23:21
 */
@Slf4j
@AllArgsConstructor
public class DynamicThreadPoolAdapterRegister implements InitializingBean {

    private final BootstrapConfigProperties bootstrapConfigProperties;

    public static final Map<String, AdapterExecutorProperties> ADAPTER_EXECUTORS_MAP = new ConcurrentHashMap<>();


    @Override
    public void afterPropertiesSet() throws Exception {
        discoverAdapterExecutor();
    }

    public AdapterExecutorProperties discoverAdapterExecutorAndGet(String mark) {
        final List<AdapterExecutorProperties> adapterExecutors = bootstrapConfigProperties.getAdapterExecutors();
        adapterExecutors.forEach(each -> {
            String buildKey = each.getMark() + IDENTIFY_SLICER_SYMBOL + each.getThreadPoolKey();
            ADAPTER_EXECUTORS_MAP.putIfAbsent(buildKey, each);
        });
        return ADAPTER_EXECUTORS_MAP.get(mark);
    }

    private void discoverAdapterExecutor() {
        final Optional<List<AdapterExecutorProperties>> adapterExecutors =
                Optional.ofNullable(bootstrapConfigProperties.getAdapterExecutors());
        adapterExecutors.ifPresent(props -> {
            props.forEach(each -> {
                String buildKey = each.getMark() + IDENTIFY_SLICER_SYMBOL + each.getThreadPoolKey();
                ADAPTER_EXECUTORS_MAP.put(buildKey, each);
            });
        });
    }
}
